
import React from 'react'
import { Menu, Dropdown, message } from 'antd'
import { CheckOutlined } from '@ant-design/icons'
import Store from '@/utils/store'
import FileInput from '@/component/fileInput'
import imgLogo from '@/assets/logo.png'
import connect from '@/utils/easyDva'
import { lintFileTree } from '@/utils/files'
import styles from './index.less'

// 菜单工具栏
function MenuTool(props) {
  const { tagsList, fileTree, isShowEditTagsModal, currentTagsName, onAddTags, onOpenFolder, setField } = props

  // 切换约束规则
  const handleChangeTagsItem = async (tagsItem) => {
    setField({
      currentTags: tagsItem.tags || {},
      currentTagsName: tagsItem.name,
      isShowEditTagsModal: false // 切换规则之后直接隐藏调整约束规则面板
    })
    Store.saveLastTagsName(tagsItem.name)

    if (tagsItem.tags) {
      const newTree = await lintFileTree(fileTree, tagsItem.tags)
      setField({
        fileTree: [...newTree]
      })
    }
    return
  }

  /**
   * 开启或者关闭编辑约束规则的弹窗
   */
  const handleSwitchEditModal = () => {
    if (!isShowEditTagsModal && !currentTagsName) {
      message.error('调整约束规则前，请先选择约束规则')
    }
    setField({
      isShowEditTagsModal: !isShowEditTagsModal
    })
  }

  // 文件菜单
  const fileMenu = (
    <Menu>
      <Menu.Item key="openFolder">
        <FileInput onChange={onOpenFolder}>
          <span className={styles.openFolder}>打开文件夹</span>
        </FileInput>
      </Menu.Item>
    </Menu>
  );

  // 约束规则菜单
  const tagsMenu = (
    <Menu>
      {
        tagsList.length > 0 ? tagsList.map((tagsItem) => {
          return <Menu.Item key={tagsItem.name} onClick={() => {
            handleChangeTagsItem(tagsItem)
          }}>{tagsItem.name === currentTagsName && <CheckOutlined className={styles.checked} />}{tagsItem.name}</Menu.Item>
        }) : <Menu.Item key="noTags" disabled>暂无约束规则</Menu.Item>
      }
      <Menu.Divider />
      <Menu.Item key="addNewTags" onClick={onAddTags}>新增约束规则</Menu.Item>
      <Menu.Item key="editTags" onClick={handleSwitchEditModal}>{isShowEditTagsModal && <CheckOutlined className={styles.checked} />}调整约束规则</Menu.Item>
    </Menu>
  );

  // 跳转到B站的视频
  const goBiliBili = () => {
    window.open('https://space.bilibili.com/36042015')
  }

  return (
    <div className={styles.container}>
      <img src={imgLogo} className={styles.imglogo} onClick={goBiliBili} alt="dog" title="野狗道人韩子卢" />
      <Dropdown overlay={fileMenu} trigger={['click']}>
        <span className={styles.btnMenu}>文件</span>
      </Dropdown>
      <Dropdown overlay={tagsMenu} trigger={['click']}>
        <span className={styles.btnMenu}>约束规则</span>
      </Dropdown>
    </div>
  );
}
export default connect(MenuTool)
